import pyttsx3
import os
import time
from typing import List

class TTSRateTester:
    def __init__(self):
        # 每次生成音频都重新初始化引擎，避免状态污染
        self.output_dir = "rate_test_samples"
        os.makedirs(self.output_dir, exist_ok=True)
        
        # 测试用文本
        self.test_text = """ Excuse me, sir, is there a commode
Justin
   Quick, honey, take my picture. I got the pyramid in my hand.
Justin  Justin, you get back here right now
  No, stop
        No, no Stop him  Go back Don't climb"""

    def _init_engine(self):
        """单独的引擎初始化方法，每次生成音频都创建新引擎"""
        try:
            engine = pyttsx3.init()
            # 配置引擎参数
            engine.setProperty('volume', 1.0)  # 确保音量正常
            
            # 选择英语语音
            english_voices = []
            for voice in engine.getProperty('voices'):
                if hasattr(voice, 'languages') and voice.languages:
                    is_english = any('en' in lang.lower() for lang in voice.languages)
                elif hasattr(voice, 'language'):
                    is_english = 'en' in voice.language.lower()
                else:
                    is_english = False
                    
                if is_english:
                    english_voices.append(voice)
            
            if english_voices:
                engine.setProperty('voice', english_voices[33].id)
                print(f"使用语音包：{english_voices[33].name}")
            
            return engine
        except Exception as e:
            raise RuntimeError(f"TTS引擎初始化失败：{str(e)}")

    def test_rates(self, rates: List[int] = None):
        """测试指定的语速列表，每次使用新引擎"""
        if not rates:
            rates = list(range(50, 350, 50))
            
        print(f"开始测试语速值：{rates}")
        
        for i, rate in enumerate(rates):
            try:
                # 每次都创建新的引擎实例
                engine = self._init_engine()
                
                # 设置当前语速
                engine.setProperty('rate', rate)
                
                # 输出文件路径
                output_path = os.path.join(self.output_dir, f"rate_{rate}.wav")
                
                # 生成音频
                engine.save_to_file(self.test_text, output_path)
                engine.runAndWait()
                
                # 确保引擎完成处理
                engine.stop()
                del engine  # 释放资源
                
                # 验证文件是否有效
                if os.path.exists(output_path) and os.path.getsize(output_path) > 1000:
                    print(f"✅ 已生成：{output_path}（大小：{os.path.getsize(output_path)/1024:.2f} KB）")
                else:
                    print(f"❌ 生成的文件无效：{output_path}")
                
                # 间隔一段时间，避免系统资源竞争
                if i < len(rates) - 1:
                    time.sleep(1)
                    
            except Exception as e:
                print(f"❌ 测试语速 {rate} 失败：{str(e)}")
        
        print(f"\n所有测试样本已保存到：{os.path.abspath(self.output_dir)}")

if __name__ == "__main__":
    tester = TTSRateTester()
    
    # 建议先测试较少的语速值
    tester.test_rates([80,90,100,120, 130, 140, 150])
    
    # 如果稳定，再扩大范围
    # tester.test_rates([80, 100, 120, 140, 160, 180, 200])
